package org.lanlab.storode.controller;

import org.lanlab.storode.common.CommonResult;
import org.lanlab.storode.controller.request.NewPageRequest;
import org.lanlab.storode.dal.entity.Page;
import org.lanlab.storode.dal.entity.Requirement;
import org.lanlab.storode.service.PageService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author dove
 * @since 2020/1/9 12:00
 */
@RestController
@RequestMapping("/pages")
public class PageController {

    private final PageService pageService;

    public PageController(PageService pageService) {
        this.pageService = pageService;
    }

    @GetMapping
    public CommonResult<List<Page>> listAllPages() {
        return CommonResult.success(pageService.listAllPages());
    }

    @GetMapping("/{id}/children")
    public CommonResult<List<Page>> listChildrenPages(@PathVariable Long id) {
        return CommonResult.success(pageService.listChildrenPages(id));
    }

    @PostMapping
    public CommonResult<String> addPage(@RequestBody NewPageRequest newPageRequest) {
        Page page = pageService.addPage(newPageRequest);
        return Objects.nonNull(page.getId()) ?
                CommonResult.success("page add successfully") : CommonResult.failed();
    }

    @PostMapping("/{id}/link/{requirementNo}")
    public CommonResult<String> linkPageToRequirement(@PathVariable Long id,
                                                      @PathVariable String requirementNo) {
        return pageService.linkRequirementToPage(id, requirementNo) ?
                CommonResult.success("link successfully") : CommonResult.failed();
    }

    @GetMapping("/{id}/requirements")
    public CommonResult<List<Requirement>> listRequirementsByPageId(@PathVariable Long id) {
        return CommonResult.success(pageService.getRequirementByPageId(id));
    }

}
